<template>
  <el-dialog title="添加"  :close-on-click-modal="false" :visible.sync="show"
   class="dialog_index dialog_banner site_fixed"
   :before-close="cancle">
   <el-form ref="bannerForm" v-loading="loading" class="product">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane :label="item.site" :name="item.site" v-for="item  in formList" :key="item.id">
            <el-form-item label="标题：" >
              <el-input type="textarea" :autosize="{ minRows: 3}" resize="none" :placeholder="'标题('+item.site+')（必填项)'" v-model="item.title"></el-input>
            </el-form-item>
            <el-form-item label="介绍描述：">
              <el-input type="textarea" :autosize="{ minRows: 3}" resize="none" :placeholder="'介绍描述('+item.site+')（非必填项)'" v-model="item.description"></el-input>
            </el-form-item>
            <el-form-item label="产品型号名称：">
              <el-input :placeholder="'产品型号名称（必填项)'" v-model="item.product_model_name"  @change="changeProductModelName"></el-input>
            </el-form-item>
            <el-form-item label="产品编码：" class="multipleSelect">
              <el-select v-model="item.product_name_show"  clearable filterable multiple  :placeholder="'产品编码（必填项)'" @focus="getProductName"  @change="changeProductName">
                <el-option v-for="product in productNameList" :key="product.value" :value="product.value" :label="product.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="一级类型：">
              <el-select v-model="item.first_product_id"  :placeholder="'一级类型（必填项)'" @clear="clearFirstType"  clearable
               @change="(value)=>changeFirstType(value, item)">
                <el-option v-for="item in item.firstTypeList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级类型：">
              <el-select v-model="item.second_product_id"  filterable :placeholder="'二级类型（必填项)'" @clear="clearSecondType"  clearable @change="changeSecondType">
                <el-option v-for="item in item.secondTypeList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item  :label="curImportExportType === 1 ? 'Input：' :'Male：'"  class="input_formitem"
             v-show="curImportExportType > 0"  >
              <div class="input_container">
                <div v-for="child in item.importList" :key="child"  @click="child.isCanChoose && changeImportExport(child, item.importExportList,item.import_product_id)"
                :class="{ 'actived': item.import_product_id.toString() === child.product_id.toString() , 'disabled': !child.isCanChoose}">
                  <el-image  :src="child.import_image"></el-image>
                  <p>{{child.import_name}}</p>
                </div> 
              </div>
            </el-form-item>
             <el-form-item :label="curImportExportType === 1 ? 'Output：' :'Female：'" class="output_formitem"
              v-show="curImportExportType > 0" >
              <div class="output_container"> 
                <div v-for="child in item.exportList" :key="child"  @click="child.isCanChoose && changeExportImport(child, item.importExportList,item.export_product_id)"
                :class="{ 'actived':  item.export_product_id.toString() === child.product_id.toString(), 'disabled': !child.isCanChoose}">
                  <el-image :src="child.export_image"></el-image> 
                  <p>{{child.export_name}}</p>
                </div>
                </div>
            </el-form-item>
             <el-form-item label="材质名称：">
              <el-select  v-model="item.material_product_id" placeholder="材质名称（非必填项)" clearable  
              @keyup.enter.native="getTableList" @clear="clearMaterialName" @change="(value)=>changeMaterialName(value)">
                <el-option v-for="item in item.materialNameList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
     
             <el-form-item label="设置链接：">
              <el-input :placeholder="'设置链接（必填项)'" v-model="item.set_link" @change="changeSetLink"></el-input>
            </el-form-item>
            <el-form-item label="说明书类型：">
              <el-select v-model="item.instructions_product_id"  :placeholder="'说明书类型（非必填项)'"  
               @change="(value)=>changeInstructionsType(value)" clearable @clear="clearInstructionsType">
                <el-option v-for="item in item.instructionList" :key="item.id" :value="item.product_id" :label="item.label"></el-option>
              </el-select>
            </el-form-item>

        </el-tab-pane>
      </el-tabs>
     
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" :loading="is_submit" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
   </el-dialog>
</template>

<script>
import { siteListGet } from '@/api/manage/site.js'
import { extendObj } from '@/utils/index'
import { productBasicAdd, erpProducNameList } from '@/api/product/productBasic.js'
import { allFirstTypeList, allSecondTypeList } from '@/api/product/productType.js'
import { importExportList } from '@/api/product/productImportExport.js'
import { allInstructionsTypeList } from '@/api/product/instructions.js'
import { AllNameList } from '@/api/product/material.js'

export default {
  data () {
    return {
      formList:[],
      loading: false,
      activeName: '',
      firstTypeList: [], //一级类型下拉框
      secondTypeList: [], //二级类型下拉框
      productNameList: [], //产品编码下拉框
      is_submit : false,
      curImportExportType: 0, //当前进出口类型
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getSite()
      }
    }
  },
  computed: {
  
  },

  methods: {
    getAllMaterialNameList(){ //获取所有站点的材质名称
      AllNameList().then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          list[i].materialNameList = data[list[i].site_id]
        }
        this.formList = list
      })
    },
    clearInstructionsType (){ //清除说明书类型
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].instructions_type = ""
        list[i].instructions_product_id = ''
      }
      this.formList  = list
    },
    getAllInstructionsTypeList(){ //获取所有站点的说明书类型
      allInstructionsTypeList().then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          list[i].instructionList = data[list[i].site_id]
        }
        this.formList = list
      })
    },
    changeInstructionsType(value){
      let list = this.formList //所有站点说明书类型赋值
      for (let i = 0; i <  list.length; i++){
        list[i].instructions_product_id = value
        for(let j = 0; j < list[i].instructionList.length; j++ ){
          let item = list[i].instructionList[j]
          if(value == item.product_id){
            list[i].instructions_type = item.value
          }
        }
      }
      this.formList = list
    },
    changeExportImport(child, importExportList, export_product_id){//export选中
      let list = this.formList
      if(export_product_id == child.product_id) { // 选中了以后再次点击
        for(let i = 0; i < list.length; i++ ){
          list[i].export_product_id = ''
          let importList = list[i].importList
          for(let j = 0; j < importList.length; j++){
            importList[j].isCanChoose = true
          }
          list[i].importList  = importList
          this.$set(this.formList, i, list[i])
        }
      } else {
        let export_name = child.export_name
        let product_ids = [] // 获取product_id列表
        for(let i = 0; i < importExportList.length; i ++ ){
          if(export_name === importExportList[i].output_name || export_name === importExportList[i].female_name ){
            product_ids.push(importExportList[i].product_id)
          }
        }
        for(let i = 0; i < list.length; i++ ){
          let importList = list[i].importList
          for(let j = 0; j < importList.length; j++){
            let productIdList = importList[j].product_id
            let isInProducts = productIdList.filter(function(item){
              return product_ids.indexOf(item) != -1
            }) 
            importList[j].isCanChoose = isInProducts.length > 0
          }
          list[i].importList  = importList
          list[i].export_product_id = child.product_id
         
          let isInExport = list[i].export_product_id.filter(function(item){
            return list[i].import_product_id.indexOf(item) != -1
          }) 
          if(isInExport.length == 0){
            list[i].import_product_id = ''
          }
          this.$set(this.formList, i, list[i])
        }
      }
    },
    changeImportExport (child, importExportList, import_product_id){ // import选中
    // child 当前点击input对象 importExportList 当前站点进出口关联表
      let list = this.formList
      if(import_product_id == child.product_id) { // 选中了以后再次点击
        for(let i = 0; i < list.length; i++ ){
          list[i].import_product_id = ''
          let exportList = list[i].exportList
          for(let j = 0; j < exportList.length; j++){
            exportList[j].isCanChoose = true
          }
          list[i].exportList  = exportList
          this.$set(this.formList, i, list[i])
        }
      } else {
        let import_name = child.import_name
        let product_ids = [] // 获取product_id列表 根据进口名称获取所有的product_id
        for(let i = 0; i < importExportList.length; i ++ ){
          if(import_name === importExportList[i].input_name || import_name === importExportList[i].male_name ){
            product_ids.push(importExportList[i].product_id)
          }
        }
        for(let i = 0; i < list.length; i++ ){ //根据product_id 查看 exportList的元素是否可选
          let exportList = list[i].exportList
          for(let j = 0; j < exportList.length; j++){
            let productIdList = exportList[j].product_id // 看出口product_id 是否存在于product_ids
            let isInProducts = productIdList.filter(function(item){
              return product_ids.indexOf(item) != -1
            }) 
            exportList[j].isCanChoose = isInProducts.length > 0
          }
          list[i].exportList  = exportList
          list[i].import_product_id = child.product_id
          let isInExport = list[i].import_product_id.filter(function(item){
            return list[i].export_product_id.indexOf(item) != -1
          }) 
          if(isInExport.length == 0){
            list[i].export_product_id = ''
          }
          this.$set(this.formList, i, list[i])
        }
    
      }
    },
    getImportExportList(first_product_id, second_product_id) { //获取所有站点进出口类型
      let params = {
        first_product_id: first_product_id,
        second_product_id: second_product_id
      }
      importExportList(params).then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          let importList = data.import[list[i].site_id]
          if(importList && importList.length > 0){
            for(let j = 0; j < importList.length; j++ ){
              importList[j].isCanChoose = true
            }
          }
          list[i].importList = importList
          let exportList = data.export[list[i].site_id]
          if(exportList && exportList.length > 0){
            for(let j = 0; j < exportList.length; j++ ){
              exportList[j].isCanChoose = true
            }
          }
          list[i].exportList = exportList
          list[i].importExportList = data.data[list[i].site_id]
        }
        let importExportList = data.data
        let type = ''
        for(let item in importExportList) {
          type = importExportList[item][0].import_export_type
        }
        this.formList = list
        this.curImportExportType = type
      })
    },
    getAllFirstTypeList() { // 获取所有站点一级类型
      allFirstTypeList().then(res=>{
        let data = res.data
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          list[i].firstTypeList = data[list[i].site_id]
        }
        this.formList = list
      })
    },
    getAllSecondTypeList(item, value) {// 获取所有站点二级类型
      let firstTypeList = item.firstTypeList
      let product_ids= []  //根据当前一级类型获取二级类型
      for(let i = 0; i < firstTypeList.length; i++) {
        if(firstTypeList[i].product_id == value){
          product_ids = firstTypeList[i].product_ids
        }
      }
      let params = {
        product_ids: product_ids
      }
      allSecondTypeList(params).then(res=>{
        let data = res.data
        let list = this.formList 
        for(let i = 0; i < list.length; i++){
          list[i].secondTypeList = data[list[i].site_id]
        }
        this.formList = list
      })
    },
    changeSetLink (value) {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].set_link = value
      }
      this.formList = list
    },
    changeProductName (value) {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].product_name_show = value
      }
      this.formList = list
    },
    getProductName () {
       erpProducNameList().then(res=>{
        if(res.state == 1){
          this.productNameList = res.data
        }
      })
    },
    changeProductModelName (value) {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].product_model_name = value
      }
      this.formList = list
    },
    //一级类型改变时同步所有站点，并获取二级类型的下拉框数据
    changeFirstType (value, item) {
      this.curImportExportType = 0
      let list = this.formList //所有站点一级类型赋值
      for (let i = 0; i <  list.length; i++){
        list[i].first_product_id = value
        list[i].second_product_id = ''
        list[i].second_type = ''
        list[i].secondTypeList = []
        list[i].importList = []
        list[i].exportList = []
        list[i].import_product_id = ''
        list[i].export_product_id = ''
        list[i].export_name = ''
        list[i].import_name = ''
        for(let j = 0; j < list[i].firstTypeList.length; j++ ){
          let item = list[i].firstTypeList[j]
          if(value == item.product_id){
            list[i].first_type = item.value
          }
        }
      }
      this.formList = list
      this.getAllSecondTypeList(item, value)  //获取二级类型的参数  

    },
    //二级类型改变时同步所有站点，并获取进出口类型所有站点的数据
    changeSecondType (value) {
      this.curImportExportType = 0
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].second_product_id = value
        list[i].importList = []
        list[i].exportList = []
        list[i].import_product_id = ''
        list[i].export_product_id = ''
        list[i].export_name = ''
        list[i].import_name = ''
        for(let j = 0; j < list[i].secondTypeList.length; j++ ){
          let item = list[i].secondTypeList[j]
          if(list[i].second_product_id == item.product_id){
            list[i].second_type = item.value
          }
        }
      }
      this.formList = list
      let first_product_id = list[0].first_product_id
      let second_product_id = list[0].second_product_id
      if(second_product_id && first_product_id) {
        this.getImportExportList(first_product_id, second_product_id)
      }
    },
    changeMaterialName (value){ //材质名称改变
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].material_product_id = value
        for(let j = 0; j < list[i].materialNameList.length; j++ ){
          let item = list[i].materialNameList[j]
          if(list[i].material_product_id == item.product_id){
            list[i].material_name = item.value
          }
        }
      }
      this.formList = list

    },
    clearMaterialName (){ //材质名称清空 清除其他站点的数据
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].material_name = ""
        list[i].material_product_id = ''
      }
    },
    clearFirstType () {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].second_type = ""
        list[i].importList = []
        list[i].exportList = []
        list[i].import_product_id = ''
        list[i].export_product_id = ''
        this.curImportExportType = 0
      }
    },
    clearSecondType () {
      let list = this.formList 
      for (let i = 0; i <  list.length; i++){
        list[i].second_type = ""
        list[i].importList = []
        list[i].exportList = []
        list[i].import_product_id = ''
        list[i].export_product_id = ''
        this.curImportExportType = 0
      }
    },
    getSite (){
      siteListGet().then(res=>{
        if (res.status == 200) {
          let data = res.data
          for(let i = 0; i < data.length; i++){
            let obj = {
              title: '',
              description: '',
              product_model_name: '',
              product_name: null,
              product_name_show: null,
              first_type: '',
              second_type: '',
              set_link:'',
              status: 2,
              tag_type: 0,
              second_product_id:'',
              first_product_id: '',
              firstTypeList: [], //一级类型下拉框
              secondTypeList: [], //二级类型下拉框
              importList:[], // 所有输入口
              exportList:[],// 所有输出口
              importExportList:[],// 输入口输出口关联列表
              instructionList: [], //说明书类型
              product_import_export_type_id: '' ,//进出口类型
              instructions_product_id:'', //说明书product_id
              instructions_type: '',//说明书类型
              import_product_id: '', //入口product_id
              export_product_id: '', //出口product_id
              import_name: '',
              export_name: '',
              material_product_id:'', //材质product_id
              materialNameList: [], //材质名称
            }
            extendObj(data[i], obj)
            data[i].site_id = data[i].id
            // this.getFirstTypeList(null, data[i])
            if (i == 0){
              this.activeName= data[i].site
            } 
          }
          this.formList= data
          this.getAllFirstTypeList()
          this.getAllInstructionsTypeList()
          this.getAllMaterialNameList()
          this.loading = false
        }

      })
    },
    submitForm () {
      let list = this.formList
      for (let i = 0; i <  list.length; i++){
        let product_name_show = list[i].product_name_show
        if(product_name_show){
          list[i].product_name = product_name_show.toString()
        }
        // list[i].product_import_export_type_id = list[i].import_product_id
        list[i].product_import_export_type = this.curImportExportType
        // 通过list[i].import_product_id 在importList查找出对应的import_name
        let importList = list[i].importList
        if(importList && importList.length > 0){
          for(let j = 0 ; j <  importList.length; j++){
            if(importList[j].product_id == list[i].import_product_id) {
              list[i].import_name = importList[j].import_name
            }
          }
        }
        // 通过list[i].export_product_id 在exportList查找出对应的export_name
        let exportList = list[i].exportList
        if(exportList && exportList.length > 0){
          for(let j = 0 ; j <  exportList.length; j++){
            if(exportList[j].product_id == list[i].export_product_id) {
              list[i].export_name = exportList[j].export_name
            }
          }
        }
//根据import_name、export_name 获取product_id存在product_import_export_type_id
        let importExportList = list[i].importExportList
        if(importExportList && importExportList.length > 0){
          for(let j = 0 ; j <  importExportList.length; j++){
            let importName = list[i].import_name == importExportList[j].input_name || list[i].import_name == importExportList[j].male_name
            let exportName = list[i].export_name == importExportList[j].output_name || list[i].export_name == importExportList[j].female_name
            if(importName && exportName) {
              list[i].product_import_export_type_id = importExportList[j].product_id
            }
          }
        }

      }
      this.formList = list
      let status = this.validateForm()
      if(status && !this.is_submit){
        this.addBannerArticle()
      }
    },
    addBannerArticle () {
      let list = JSON.parse(JSON.stringify(this.formList)) 
      for( let i = 0; i < list.length; i++){
        delete list[i].firstTypeList
        delete list[i].secondTypeList
        delete list[i].importExportList
        delete list[i].instructionList
        delete list[i].importList
        delete list[i].exportList
        delete list[i].materialNameList
      }
      let params = {
        data: JSON.stringify(list) 
      }
      this.is_submit = true
      productBasicAdd(params).then(res => {
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
        this.is_submit = false
      })
    },
    validateForm () {
      let list = this.formList

      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].title === '') {
          this.$message.error('站点' + list[i].site + '标题为必填项')
          status = false
          break
        }
        if (list[i].product_model_name === '') {
          this.$message.error('站点' + list[i].site + '产品型号名称为必填项')
          status = false
          break
        }

        if (list[i].product_name === '') {
          this.$message.error('站点' + list[i].site + '产品编码为必填项')
          status = false
          break
        }
        if (list[i].first_type === '') {
          this.$message.error('站点' + list[i].site + '一级类型为必填项')
          status = false
          break
        }
        if (list[i].second_type === '') {
          this.$message.error('站点' + list[i].site + '二级类型为必填项')
          status = false
          break
        }
        if (list[i].product_import_export_type > 0) {  // 进出口存在的情况下为必填项
          if (list[i].import_product_id === '') {
            let word = ''
            if(this.curImportExportType == 1){
              word = '站点' + list[i].site + 'Input为必填项'
            } else {
              word = '站点' + list[i].site + 'Male为必填项'
            }
            this.$message.error(word)
            status = false
            break
          }
          if (list[i].export_product_id === '') {
            let word = ''
            if(this.curImportExportType == 1){
              word = '站点' + list[i].site + 'Output为必填项'
            } else {
              word = '站点' + list[i].site + 'Female为必填项'
            }
            this.$message.error(word)
            status = false
            break
          }
        }
        if (list[i].set_link === '') {
          this.$message.error('站点' + list[i].site + '设置链接为必填项')
          status = false
          break
        }
      }
      return status
    },
    
    cancle(){
      // this.$refs.addSiteFrom.clearValidate();
      this.$emit('closeDialog')
      this.curImportExportType = 0
      this.$refs.bannerForm.resetFields(); // 清空原来的数据
    },
  },
 
}
</script>

<style lang="scss">

</style>